package org.wattdepot.cli.command;

import java.util.List;
import java.text.DecimalFormat;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Class for Carbon Content for a source.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 * 
 */
public class CarbonContent extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Command 2.13 - Displays carbon content of the specified source based on the specified timestamp
   * and sampling interval.
   * 
   * @param args - List of parameters read in from the command line.
   * @return - String containing the carbon content.
   */
  public String doCommand(List<String> args) {
    String source = args.get(0);
    String timestamp = args.get(1);
    Double carbonGenerated = null;
    Double energyGenerated = null;
    Double carbonContent = null;
    XMLGregorianCalendar startTime = null;
    XMLGregorianCalendar endTime = null;
    StringBuffer buff = new StringBuffer(255);
    DecimalFormat d = new DecimalFormat("#.#");

    try {

      Integer samplingInterval = Integer.parseInt(args.get(2));

      // Declare start and end times
      startTime = Tstamp.makeTimestamp(timestamp);
      endTime = Tstamp.incrementHours(startTime, 1);

      // Get total carbon generated for the hour
      carbonGenerated = client.getCarbonEmitted(source, startTime, endTime, samplingInterval);

      // Get total energy generated for the hour
      energyGenerated = client.getEnergyGenerated(source, startTime, endTime, samplingInterval);

      // Convert to MW-hours
      energyGenerated = energyGenerated / 1000000;

      // Check if energy generated is 0
      if (energyGenerated == 0) {
        buff.append("Carbon content not available.");
      }
      else {
        // Calculate carbon content
        carbonContent = (carbonGenerated / energyGenerated);

        // Append result to output buffer
        buff.append(d.format(carbonContent));
        buff.append(" lbs CO2/MWh");
      }

    }
    catch (MiscClientException mce) {
      return errorClient;
    }
    catch (BadXmlException bxe) {
      return errorXML;
    }
    catch (ResourceNotFoundException rnfe) {
      return error404;
    }
    catch (NotAuthorizedException nae) {
      return error401;
    }
    catch (NumberFormatException nfe) {
      return "Your specified interval is not a number";
    }
    catch (Exception e) {
      return errorTimeStamp;
    }
    return buff.toString();
  }

}
